package com.huazhi.wzsnw.service.impl;

import com.huazhi.wzsnw.service.SystemService;
import com.huazhi.wzsnw.util.MongoUtil;
import com.mongodb.BasicDBList;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.UpdateResult;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class SystemServiceImpl implements SystemService {

    MongoUtil mongoUtil = MongoUtil.instance;

    @Override
    public JSONObject getMongoStructure(Integer page, Integer pageSize, String tableName, String location) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        JSONObject jsonObject = new JSONObject();
        List<Document> list = new ArrayList<Document>();
        Document sort = new Document("oderNumber", -1);
        Document locationDo = new Document("locations", location);
        Integer index = (page - 1) * pageSize;
        FindIterable<Document> one = mongoUtil.getCollection(tableName).find(locationDo).sort(sort).skip(index).limit(pageSize);
        Long allCount = mongoUtil.getCollection(tableName).count(locationDo);

        MongoCursor<Document> mongoCursor = one.iterator();
//        Integer i = 1;
        while (mongoCursor.hasNext()) {
            Document oneDocument = mongoCursor.next();
//            oneDocument.put("number", i);
            list.add(oneDocument);
            oneDocument.put("createTime", sdf.format(oneDocument.get("createTime")));
            oneDocument.put("id", oneDocument.get("_id").toString());
//            i++;
        }
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        jsonObject.put("count", allCount);
        jsonObject.put("data", list);


        return jsonObject;
    }


    @Override
    public Boolean getValueExsit(String tableName, String key, String value) {

        Document search = new Document(key, value);
        Long allCount = mongoUtil.getCollection(tableName).count(search);
        if (allCount > 0) {
            return false;
        } else {
            return true;
        }

    }


//    @Override
//    public Boolean getCodeExsitForExcel(String tableName, String key, String value, String id) {
//        Document search = new Document("selectName", key);
//        search.put("optionName", value);
//        search.put("selectTid", id);
//        Long allCount = mongoUtil.getCollection(tableName).count(search);
//        if (allCount > 0l) {
//            return false;
//        } else {
//            return true;
//        }
//    }

    @Override
    public Boolean getCodeExsit(String tableName, String key, String value, String id) {
        Document search = new Document(key, value);

        search.put("selectTid", id);
        Long allCount = mongoUtil.getCollection(tableName).count(search);
        if (allCount > 0l) {
            return false;
        } else {
            return true;
        }

    }

    @Override
    public int addStructure(Map<String, Object> data, String tableName) {

        Integer result = null;
        Document doc = new Document();
        if (!data.containsKey("state")) {
            data.put("state", "off");
        }
        if (!data.containsKey("isValidate")) {
            data.put("isValidate", "off");
        }

        if (!data.containsKey("head")) {
            data.put("head", "off");
        }

        try {
            for (String oneKey : data.keySet()) {
                if (oneKey.equals("state")) {
                    if (data.get(oneKey).equals("on")) {
                        doc.put(oneKey, "1");
                    } else {
                        doc.put(oneKey, "0");
                    }
                } else if (oneKey.equals("isValidate")) {
                    if (data.get(oneKey).equals("off")) {
                        doc.put(oneKey, "no");
                    } else {
                        doc.put(oneKey, "yes");
                    }
                } else if (oneKey.equals("head")) {
                    if (data.get(oneKey).equals("on")) {
                        doc.put(oneKey, "1");
                    } else {
                        doc.put(oneKey, "0");
                    }
                }else if (oneKey.equals("oderNumber")) {
                    if (data.get(oneKey).equals("")) {
                        doc.put(oneKey, 0);
                    } else {
                        doc.put(oneKey, Integer.valueOf((String)data.get(oneKey)));
                    }
                } else {
                    doc.put(oneKey, data.get(oneKey));
                }
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            doc.put("createTime", sdf.parse((String) doc.get("createTime")).getTime());
            doc.put("dataLength", "");

            mongoUtil.getCollection(tableName).insertOne(doc);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return (1);
    }


    @Override
    public int addCode(Map<String, String> data, String tableName) {
        Integer result = null;
        Document doc = new Document();


        try {
            for (String oneKey : data.keySet()) {
                doc.put(oneKey, data.get(oneKey));
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            doc.put("createTime", sdf.parse((String) doc.get("createTime")).getTime());
            //取当前时间的长整形值包含毫秒
            long millis = System.currentTimeMillis();        //加上三位随机数
            Random random = new Random();
            int end3 = random.nextInt(999);//该方法的作用是生成一个随机的int值，该值介于[0,n]的区间，也就是0到n之间的随机int值，包含0而不包含n。
            //如果不足三位前面补0  String.format("%03d", end3); 3代表要获得的总长度，0代表传入的参数不够的时候会用0作为填充，d会被传入的参数替代
            String str = millis + String.format("%03d", end3);
            System.out.println("NO"+str);
            doc.put("optionCode","NO"+str);
            mongoUtil.getCollection(tableName).insertOne(doc);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return (1);
    }


    @Override
    public JSONObject getPlace() {
        JSONObject result = new JSONObject();
        Document query = new Document("selectName", "place");
        FindIterable<Document> one = mongoUtil.getCollection("selectTable").find(query);

        Integer allCount = 0;
        List<String> dataResult = new ArrayList<String>();

        MongoCursor<Document> mongoCursor = one.iterator();
        while (mongoCursor.hasNext()) {
            dataResult.add(mongoCursor.next().getString("optionName"));
            allCount++;
        }
        result.put("code", 0);
        result.put("msg", "");
        result.put("count", allCount);
        result.put("data", dataResult);

        return result;
    }

    @Override
    public JSONObject getOneStructure(String id, String tableName) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        JSONObject jsonObject = new JSONObject();
        List<Document> list = new ArrayList<Document>();
        Document search = new Document("_id", new ObjectId(id));

        FindIterable<Document> one = mongoUtil.getCollection(tableName).find(search);
        Long allCount = mongoUtil.getCollection(tableName).count(search);

        MongoCursor<Document> mongoCursor = one.iterator();
        while (mongoCursor.hasNext()) {
            Document oneDocument = mongoCursor.next();

            oneDocument.put("createTime", sdf.format(oneDocument.get("createTime")));
            oneDocument.put("id", oneDocument.get("_id").toString());
            if (oneDocument.get("state").equals("1")) {
                oneDocument.put("state", "on");
            } else {
                oneDocument.put("state", "");
            }
            if (oneDocument.get("isValidate").equals("yes")) {
                oneDocument.put("isValidate", "on");
            } else {
                oneDocument.put("isValidate", "");
            }
            if (oneDocument.get("head").equals("1")) {
                oneDocument.put("head", "on");
            } else {
                oneDocument.put("head", "");
            }


            list.add(oneDocument);

        }
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        jsonObject.put("count", allCount);
        jsonObject.put("data", list);


        return jsonObject;
    }


    @Override
    public int updateStructure(Map<String, Object> data, String id, String tableName) {
        try {


            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Document newObject = new Document();
            Document useNewObject = new Document();
            if (!data.containsKey("state")) {
                data.put("state", "off");

            }
            if (!data.containsKey("isValidate")) {
                data.put("isValidate", "off");

            }
            if (!data.containsKey("head")) {
                data.put("head", "off");
            }


            for (String one : data.keySet()) {
                if (one.equals("state")) {
                    if (data.get(one).equals("on")) {
                        newObject.put(one, "1");
                    } else {
                        newObject.put(one, "0");
                    }
                } else if (one.equals("isValidate")) {
                    if (data.get(one).equals("off")) {
                        newObject.put(one, "no");
                    } else {
                        newObject.put(one, "yes");
                    }
                } else if (one.equals("head")) {
                    if (data.get(one).equals("on")) {
                        newObject.put(one, "1");
                    } else {
                        newObject.put(one, "0");
                    }
                } else if (one.equals("createTime")) {
                    newObject.put("createTime", sdf.parse((String) data.get("createTime")).getTime());
                }else if (one.equals("oderNumber")) {
                    if (data.get(one).equals("")) {
                        newObject.put(one, 0);
                    } else {
                        newObject.put(one, Integer.valueOf((String)data.get(one)));
                    }
                }else {
                    newObject.put(one, data.get(one));
                }
            }


            useNewObject.put("$set", newObject);
            Document idObject = new Document("_id", new ObjectId(id));

            UpdateResult updateOneResult = mongoUtil.getCollection(tableName).updateOne(idObject, useNewObject);
            System.out.println("修改的数量: " + updateOneResult.getModifiedCount());
            if (updateOneResult.isModifiedCountAvailable()) {
                System.out.println("文档更新一个成功");
                return 1;
            } else {
                System.out.println("文档更新失败");
                return -1;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }


    @Override
    public int updateStructureState(String key, String state, String id, String tableName) {
        try {
            Document newObject = new Document();
            Document useNewObject = new Document();
            newObject.put(key, state);
            useNewObject.put("$set", newObject);
            Document idObject = new Document("_id", new ObjectId(id));

            UpdateResult updateOneResult = mongoUtil.getCollection(tableName).updateOne(idObject, useNewObject);
            System.out.println("修改的数量: " + updateOneResult.getModifiedCount());
            if (updateOneResult.isModifiedCountAvailable()) {
                System.out.println("文档更新一个成功");
                return 1;
            } else {
                System.out.println("文档更新失败");
                return -1;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }


    @Override
    public JSONArray getTreeStructure() {
        JSONArray array = new JSONArray();

        JSONObject result = new JSONObject();
        result.put("title", "属性列表");
        result.put("id", "1");
        result.put("checkArr", "0");
        result.put("parentId", "0");
        array.add(result);

        List<String> canSearchName = new ArrayList<String>();

        canSearchName.add("select");
        canSearchName.add("radio");
        canSearchName.add("selects");
        canSearchName.add("checkbox");

        BasicDBList orQueryList1 = new BasicDBList();
        for (String oneColumn : canSearchName) {
            Document oneKey = new Document();
            oneKey.put("type", oneColumn);
            orQueryList1.add(oneKey);
        }
        Document orQuery = new Document("$or", orQueryList1);
        Document sort = new Document("createTime", 1);
        FindIterable<Document> one = mongoUtil.getCollection("mainStructure").find(orQuery).sort(sort);
        MongoCursor<Document> mongoCursor = one.iterator();
        while (mongoCursor.hasNext()) {
            Document oneDocument = mongoCursor.next();
            if (!"mysql".equals(oneDocument.get("table"))) {
                JSONObject oneResult = new JSONObject();
                oneResult.put("title", oneDocument.get("displayName"));
                oneResult.put("id", oneDocument.get("_id").toString());
                oneResult.put("checkArr", "0");
                oneResult.put("parentId", "1");
                array.add(oneResult);
            }
        }

        //维保状态  单独添加  不放入mainStructure免得影响物品属性
        JSONObject oneResult = new JSONObject();
        oneResult.put("title", "维保结果");
        oneResult.put("id", "maintainStateTid");
        oneResult.put("checkArr", "0");
        oneResult.put("parentId", "1");
        array.add(oneResult);

        return array;
    }

    @Override
    public JSONObject getSelectStructure(Integer page, Integer pageSize, String tableName, String id) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        JSONObject jsonObject = new JSONObject();
        List<Document> list = new ArrayList<Document>();
        Document sort = new Document("createTime", -1);
        Document idObject = new Document("selectTid", id);

        Integer index = (page - 1) * pageSize;
        FindIterable<Document> one = null;
        Long allCount = null;
        if ("1".equals(id)) {
            one = mongoUtil.getCollection(tableName).find().sort(sort).skip(index).limit(pageSize);
            allCount = mongoUtil.getCollection(tableName).count();
        } else {
            one = mongoUtil.getCollection(tableName).find(idObject).sort(sort).skip(index).limit(pageSize);
            allCount = mongoUtil.getCollection(tableName).count(idObject);
        }


        MongoCursor<Document> mongoCursor = one.iterator();
        Integer i = 1;
        while (mongoCursor.hasNext()) {
            Document oneDocument = mongoCursor.next();
            oneDocument.put("number", i);
            list.add(oneDocument);

            oneDocument.put("createTime", sdf.format(oneDocument.get("createTime")));
            oneDocument.put("id", oneDocument.get("_id").toString());
            i++;
        }
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        jsonObject.put("count", allCount);
        jsonObject.put("data", list);

        return jsonObject;
    }


//    @Override
//    public JSONObject getOneOption(String tableName, String id) {
//        List<Document> list = new ArrayList<Document>();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        JSONObject jsonObject = new JSONObject();
//        Document query = new Document("_id", new ObjectId(id));
//        FindIterable<Document> one = mongoUtil.getCollection(tableName).find(query);
//        MongoCursor<Document> mongoCursor = one.iterator();
//        while (mongoCursor.hasNext()) {
//            Document oneDocument = mongoCursor.next();
//            oneDocument.put("createTime", sdf.format(oneDocument.get("createTime")));
//            oneDocument.put("id", oneDocument.get("_id").toString());
//            list.add(oneDocument);
//        }
//
//        jsonObject.put("code", 0);
//        jsonObject.put("msg", "");
//        jsonObject.put("count", 1);
//        jsonObject.put("data", list);
//
//        return jsonObject;
//    }


    @Override
    public void deleteAttributeById(String id, String tableName) {
        Document query = new Document("_id", new ObjectId(id));
        FindIterable<Document> one = mongoUtil.getCollection(tableName).find(query);
        MongoCursor<Document> mongoCursor = one.iterator();
        while (mongoCursor.hasNext()) {
            Document oneDocument = mongoCursor.next();
        }
        mongoUtil.getCollection("selectTable").deleteMany(Filters.eq("selectTid",new ObjectId(id)));
        mongoUtil.getCollection(tableName).deleteOne(Filters.eq("_id", new ObjectId(id)));

    }
}
